<template>
  <div class="login-container">
    <div class="login-form" v-show="!showRegister">
      <h2>用户登录</h2>
      <el-form  label-width="80px" :model="loginForm" :rules="loginRules" ref="loginFormRef" @submit.prevent="handleLogin">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        还没有账户？ <el-button type="text" @click="showRegister = true">立即注册</el-button>
      </div>
    </div>

    <!-- 注册对话框 -->
    <el-dialog v-model="showRegister" title="用户注册" width="400px" :show-close="false">
      <el-form label-width="80px" :model="registerForm" :rules="registerRules" ref="registerFormRef" @submit.prevent="handleRegister">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item class="form-bottom">
          <el-button type="primary" @click="handleRegister" :loading="registerLoading">注册</el-button>
          <el-button @click="showRegister = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { ElForm, ElFormItem, ElInput, ElButton, ElDialog, ElMessage } from 'element-plus'
import http from '@/utils/http'
import { saveAuthInfo } from '@/utils/auth'

export default {
  name: 'Login',
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElDialog
  },
  data() {
    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      registerLoading: false,
      showRegister: false,
      loginForm: {
        username: '',
        password: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async handleLogin() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            const response = await http.post('/auth/login', this.loginForm)
            ElMessage.success('登录成功')
            
            // 保存认证信息
            saveAuthInfo(response.token, response.user)
            
            // 跳转到首页或用户原本想要访问的页面
            const redirect = this.$route.query.redirect || '/'
            this.$router.push(redirect).then(() => {
              // 跳转到用户原本想要访问的页面
              window.location.reload()
            })
          } catch (error) {
            ElMessage.error(error.response?.data?.message || '登录失败')
          } finally {
            this.loading = false
          }
        }
      })
    },
    
    async handleRegister() {
      this.$refs.registerFormRef.validate(async (valid) => {
        if (valid) {
          if(this.registerForm.username.indexOf(' ') > -1){
            ElMessage.error('用户名不能包含空格');
            return;
          }
          this.registerLoading = true
          try {
            const response = await http.post('/auth/register', {
              username: this.registerForm.username,
              password: this.registerForm.password,
              phone: this.registerForm.phone
            })
            ElMessage.success('注册成功')
            
            // 保存认证信息
            saveAuthInfo(response.token, response.user)
            
            // 关闭注册对话框
            this.showRegister = false
            
            // 跳转到首页
            this.$router.push('/')
          } catch (error) {
            ElMessage.error(error.response?.data?.message || '注册失败')
          } finally {
            this.registerLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100% !important;
  justify-content: center;
  align-items: center;
  height: 60vh;
  -background: linear-gradient(135deg, rgba(255, 165, 0, 0.1) 0%, rgba(0, 102, 204, 0.1) 100%);
}

.login-form {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 102, 204, 0.15);
  border-top: 4px solid #ff8c00;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #0066cc;
  font-weight: 600;
}
.form-bottom{
  display:flex;
  width:80%;
  margin:0 auto;
}
.login-button {
  width: 100%;
  background-color: #ff8c00;
  border-color: #ff8c00;
  font-weight: 600;
  transition: all 0.3s ease;
}
:deep(.el-form-item__content){
  margin-left: 0 !important;
  place-content: space-around;
}

.login-button:hover {
  background-color: #ff7700;
  border-color: #ff7700;
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.register-link .el-button {
  color: #0066cc;
  font-weight: 600;
}

.register-link .el-button:hover {
  color: #ff8c00;
  text-decoration: underline;
}

/* 注册对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: #0066cc;
  color: white;
  padding: 10px;
  text-align: center;
}
:deep(.el-dialog__body){
  margin-top:20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-form-item__label) {
  color: #0066cc;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background-color: #ff8c00;
  border-color: #ff8c00;
}

:deep(.el-button--primary:hover) {
  background-color: #ff7700;
  border-color: #ff7700;
}
</style>